package com.ys.web.ws;

import com.ys.base.EnumType;
import com.ys.utils.base.j2se.JsonUtil;
import com.ys.utils.base.j2se.Logger;
import com.ys.utils.base.j2se.StringHandler;
import com.ys.utils.help.UserUtils;
import com.ys.web.ws.bean.MessageRequestBean;
import com.ys.web.ws.manager.ChatObjectManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * @author quxinjun
 * @version 1.0.0
 * @ClassName ChatObject.java
 * @Description ；连接对象
 * @createTime 2021年05月06日 15:16:00
 */
@Slf4j
@Component
@ServerEndpoint(value = "/chat/{uid}")
public class ChatObject {

    public Session session;

    public String userId;

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "uid") String userId) {
        if (!StringHandler.isEmpty(userId)) {
            this.userId = userId;
            //将局部的 session 赋值给成员 session
            this.session = session;
            ChatObjectManager.chatMap.put(userId, this);

            ChatObjectManager.getCurrentOnline();
            //查询缓存中  存储的对应用户的未发送的消息

        } else {
            Logger.info("未能获取到用户 id 信息，连接建立失败");
        }
    }


    @OnMessage
    public void onMessage(String message, Session session) {
        MessageRequestBean messageRequestBean = null;
        try {
            //心跳检测：谁发过来的，发送给谁
            messageRequestBean = JsonUtil.jsonToBean(message, MessageRequestBean.class);
        } catch (Exception e) {

        }
        if (messageRequestBean != null && EnumType.MessageCode.MESSAGE_CHECK_HEART.getCode().equals(messageRequestBean.getCode())) {
            //心跳检测：谁发过来的，发送给谁
            ChatObject chatObject = ChatObjectManager.chatMap.get(messageRequestBean.getFrom());
            chatObject.sendMessage(chatObject, messageRequestBean, null);
        }

    }

    public boolean sendMessage(ChatObject chatObject, MessageRequestBean messageRequestBean, String windowPrefix) {

        synchronized (chatObject.session) {
            try {
                String jsonStr = UserUtils.getMessageResponseList(messageRequestBean, windowPrefix);
                if (chatObject.session.isOpen()) {
                    chatObject.session.getAsyncRemote().sendText(jsonStr);
                }
                return true;
            } catch (Exception e) {
                Logger.info(String.format("发送消息出现异常，消息接收：{%s},消息内容：{%s}", messageRequestBean.getTo(), messageRequestBean.getData()));
                return false;
            }
        }
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) throws IOException {
        ChatObjectManager.removeChatMapByKey(this.userId);
        ChatObjectManager.getCurrentOnline();
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        ChatObjectManager.removeChatMapByKey(this.userId);
        ChatObjectManager.getCurrentOnline();
    }

    /**
     * @param messageRequestBean 消息对象
     * @title assemblyMessageResponse
     * @description 组装发送的消息
     * @author quxinjun
     * @updateTime 2021/5/7 10:23
     * @return: java.lang.String
     */
//    private String assemblyMessageResponse(MessageRequestBean messageRequestBean) {
//        LoginInfo cacheUser = UserUtils.getCacheUser(McodeHandler.from32Radix(messageRequestBean.getFrom()));
//        MessageResponseBean result = new MessageResponseBean();
//        result
//                .setCode(messageRequestBean.getCode())
//                .setUserName(cacheUser.getNickName())
//                .setAvatarUrl(cacheUser.getAvatarUrl())
//                .setData(messageRequestBean.getData())
//                .setCreateTime(messageRequestBean.getCreateTime())
//                .setFrom(StringHandler.isNotEmpty(
//                        messageRequestBean.getGroupId()) ? messageRequestBean.getGroupId()
//                        : messageRequestBean.getFrom()
//                );
//        return JsonUtil.toJson(result);
//    }

}
